﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using NormalMappingEffectPipeline;

namespace ContentPipelineExtensions
{
    [ContentProcessor]
    public class TangentComputingModelProcessor : NormalMappingModelProcessor
    {
        private string directory;
        public override ModelContent Process(Microsoft.Xna.Framework.Content.Pipeline.Graphics.NodeContent input, ContentProcessorContext context)
        {
            directory = Path.GetDirectoryName(Path.GetDirectoryName(input.Identity.SourceFilename));
            foreach (var mesh in input.Children.OfType<MeshContent>())
            {
                MeshHelper.MergeDuplicatePositions(mesh, 0.0f);
                MeshHelper.OptimizeForCache(mesh);
                MeshHelper.CalculateTangentFrames(mesh, VertexChannelNames.TextureCoordinate(0), VertexChannelNames.Tangent(0), VertexChannelNames.Binormal(0));


            }
            return base.Process(input, context);

        }

        protected override MaterialContent ConvertMaterial(MaterialContent material,
           ContentProcessorContext context)
        {
            EffectMaterialContent normalMappingMaterial = material as EffectMaterialContent;
            
            normalMappingMaterial.Effect = new ExternalReference<EffectContent>
                (Path.Combine(directory, "BabylonEffect.fx"));

            OpaqueDataDictionary processorParameters = new OpaqueDataDictionary();
            processorParameters["ColorKeyColor"] = this.ColorKeyColor;
            processorParameters["ColorKeyEnabled"] = this.ColorKeyEnabled;
            processorParameters["TextureFormat"] = this.TextureFormat;
            processorParameters["GenerateMipmaps"] = this.GenerateMipmaps;
            processorParameters["ResizeTexturesToPowerOfTwo"] =
                                                        this.ResizeTexturesToPowerOfTwo;


            // and convert the material using the NormalMappingMaterialProcessor,
            // who has something special in store for the normal map.
            return context.Convert<MaterialContent, MaterialContent>
                (normalMappingMaterial, typeof(ViperMaterialProcessor).Name,
                processorParameters);
        }

    }
}
